from mt4_client import MT4Client, OrderType
import time
from typing import Dict, Optional
import config

class SimpleStrategy:
    def __init__(self, client: MT4Client, symbol: str = "EURUSD"):
        """
        初始化简单策略
        :param client: MT4客户端
        :param symbol: 交易品种
        """
        self.client = client
        self.symbol = symbol
        self.magic = config.TRADE_CONFIG['magic']
        
        # 获取货币对特定的策略配置
        strategy_config = config.SYMBOL_STRATEGY_CONFIG.get(symbol, config.SYMBOL_STRATEGY_CONFIG['DEFAULT'])
        
        # 策略参数
        self.lots = strategy_config['lots_range']['base']  # 初始手数
        self.stop_new_orders = False  # 是否停止开启新订单
        
    def calculate_current_orders(self) -> int:
        """
        计算当前订单数量
        :return: 正数表示多单数量，负数表示空单数量，0表示无持仓
        """
        positions = self.client.get_positions()
        buys = 0
        sells = 0
        
        for pos in positions:
            if pos.symbol == self.symbol and pos.magic == self.magic:
                if pos.type == OrderType.BUY.value:
                    buys += 1
                elif pos.type == OrderType.SELL.value:
                    sells += 1
                    
        if buys > 0:
            return buys
        else:
            return -sells
            
    def open_order(self, direction: int, stop_loss: float = 0) -> bool:
        """
        开仓
        :param direction: 交易方向 (0=空单, 1=多单)
        :param stop_loss: 止损价格，默认为0表示不设置止损
        :return: 是否开仓成功
        """
        try:
            market = self.client.get_market_info(self.symbol)
            
            # 计算止盈价格（与止损点数相同）
            if direction == 1:  # 多单
                take_profit = market.ask + (market.ask - stop_loss) if stop_loss > 0 else 0
            else:  # 空单
                take_profit = market.bid - (stop_loss - market.bid) if stop_loss > 0 else 0
                
            # 开仓
            response = self.client.open_order(
                symbol=self.symbol,
                type=direction,
                lots=self.lots,
                sl=stop_loss,
                tp=take_profit,
                magic=self.magic
            )
            
            print(f"开仓成功: {response}")
            return True
            
        except Exception as e:
            print(f"开仓失败: {str(e)}")
            return False
            
    def close_all_orders(self) -> None:
        """平掉所有订单"""
        positions = self.client.get_positions()
        for pos in positions:
            if pos.symbol == self.symbol and pos.magic == self.magic:
                self.client.close_order(pos.ticket)
                
    def run(self) -> None:
        """运行策略"""
        try:
            print(f"开始运行简单策略，交易品种: {self.symbol}")
            print("按 Ctrl+C 停止策略")
            
            while True:
                # 检查是否有持仓
                current_orders = self.calculate_current_orders()
                if current_orders != 0:
                    print(f"当前有持仓: {current_orders}")
                    time.sleep(1)  # 等待1秒后再次检查
                    continue
                    
                # 短暂休眠，避免CPU占用过高
                time.sleep(0.1)
                
        except KeyboardInterrupt:
            print("\n停止策略...")
        except Exception as e:
            print(f"发生错误: {str(e)}")
        finally:
            print("策略已停止")

    def stop(self) -> None:
        """停止策略"""
        self.stop_new_orders = True
        print("策略停止开启新订单") 